import java.util.Stack;

public class Main {
    public static void main(String[] args) {
        Main main = new Main();
        int[] arr={2,3,1,2,4,3};
        int target=7;
        System.out.println(main.minSubArrayLen(target,arr));
    }

    //时间超时
    public int minSubArrayLen1(int target, int[] nums) {
       int min=Integer.MAX_VALUE;
        for(int i=0; i<nums.length; i++){
            int count=0;int sum=0;
            for(int j=i; j<nums.length; j++){
                sum+=nums[j];
                count++;
                if(sum>=target){
                    min=Math.min(min,count);
                    break;
                }
            }
        }
        return min==Integer.MAX_VALUE?0:min;
    }

    public int minSubArrayLen(int target, int[] nums) {
        int n=nums.length;
        if(n==0) return 0;
        int end=0;int start=0;int sum=0;int ans=Integer.MAX_VALUE;
        while(end<n){
            sum+=nums[end];
            while(sum>=target){
                ans=Math.min(ans,end-start+1);
                sum-=nums[start];
                start++;
            }
            end++;
        }
        return ans == Integer.MAX_VALUE?0:ans;
    }

    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        Stack<TreeNode> s1=new Stack<>();
        Stack<TreeNode> s2=new Stack<>();
        getPath(root,p,s1);
        getPath(root,q,s2);
        if(s1.size()>s2.size()){
            int len=s1.size()-s2.size();
            while(len!=0){
                s1.pop();
                len--;
            }
        }else{
            int len=s2.size()-s1.size();
            while(len!=0){
                s2.pop();
                len--;
            }
        }
        while(!s1.isEmpty()&&!s2.isEmpty()){
            if(s1.peek()==s2.peek()){
                return s1.peek();
            }else{
                s1.pop();
                s2.pop();
            }
        }
        return null;
    }
    public boolean getPath(TreeNode root,TreeNode target,Stack<TreeNode> stack){
        if(root==null) return false;
        stack.push(root);
        if(root==target) return true;
        if(getPath(root.left,target,stack)){
            return true;
        }
        if(getPath(root.right,target,stack)){
            return true;
        }stack.pop();
        return false;
    }

      static class TreeNode {
      int val;
      TreeNode left;
      TreeNode right;
      TreeNode(int x) { val = x; }
  }
}